package com.intellagric.controller.page;

import com.alibaba.dubbo.common.json.JSONObject;
import com.intellagric.common.jedis.JedisClient;
import com.intellagric.common.jedis.JedisClientPool;
import com.intellagric.common.pojo.ResponseMessage;
import com.intellagric.common.utils.CookieUtils;
import com.intellagric.common.utils.JsonUtils;
import com.intellagric.pojo.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: zhy
 * @email: 1269679946@qq.com
 * @Date: 2019/1/22
 * @DESC： 权限过滤
 */

public class AdminFilter implements Filter {

    /*@Autowired
    private JedisClient jedisClient;*/

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取cookie
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String token = CookieUtils.getCookieValue(httpServletRequest, "token", false);

        //获取用户数据
        ApplicationContext context = new ClassPathXmlApplicationContext("spring/applicationContext-redis.xml");
        JedisClientPool jedisClientPool = (JedisClientPool)context.getBean("jedisClientPool");
        String user = jedisClientPool.get("SESSION:" + token);
        if (StringUtils.isBlank(user)) {
            //用户登录已过期
            httpServletResponse.sendRedirect("/direction");
        } else {
            SysUser sysUser = JsonUtils.jsonToPojo(user, SysUser.class);
            //设置companyId
            String userType = sysUser.getUserType();
            CookieUtils.setCookie(httpServletRequest,httpServletResponse,"companyId",sysUser.getCompanyId());

            if (userType.equals("0")) {//系统用户
                filterChain.doFilter(servletRequest,servletResponse);
            } else {
                httpServletResponse.sendRedirect("/direction");
            }
        }

    }

    @Override
    public void destroy() {

    }

}